

import { TTPathTool } from "./pathtool";

export class FormatInfo {
    constructor(ext: string, path_html: string, initscript: string) {
        this.ext = ext;
        this.path_html = path_html;
        this.initscript = initscript;

    }
    ext: string = "";
    path_html: string = "";

    initscript: string = "main.js";
}


export class FormatMgr {

    private constructor() {


        //如果一个文件格式只对应一个扩展名，那么可以直接用下面这个
        this.RegFormatInfo(new FormatInfo(".ttatlas.json", "htmlview", "pack_atlaspack.js"));

        //否则你就需要用正则表达式
        //let reg = FormatMgr.MakeRegExp(".ttatlas.json", ".png");
        //this.RegFormatInfo(new FormatInfo(reg, "./htmlview", "atlaspack.js"));

        this.RegFormatInfo(new FormatInfo(".png", "htmlview", "pack_pixeledit.js"));
        //this.RegFormatInfo(new FormatInfo(".ttimg.json", "htmlview", "pack_pixeledit.js"));
        this.RegFormatInfo(new FormatInfo(".ttani.json", "htmlview", "pack_ttani.js"));
    }
    static replacedot(src: string): string {
        let step1 = src;
        while (step1.includes("."))
            step1 = step1.replace(".", "*");

        let step2 = step1;
        while (step2.includes("*"))
            step2 = step2.replace("*", "\\.");
        return step2;
    }
    static MakeRegExp(...exts: string[]): string {
        if (exts.length < 1)
            throw new Error("一个扩展名都没有是不行的")

        let reg = ".+(";
        if (exts.length == 1) {
            exts[0].replace(".", "\\.");
            reg += this.replacedot(exts[0]);
        }
        else {
            for (let i = 0; i < exts.length; i++) {
                if (i > 0)
                    reg += "|";
                reg += "(" + this.replacedot(exts[i]) + ")";
            }
        }
        reg += ")$";
        return reg;
    }
    //单例
    private static _instance: FormatMgr | null = null;
    static Instance(): FormatMgr {
        if (this._instance == null) {
            this._instance = new FormatMgr();
        }
        return this._instance;
    }


    RegFormatInfo(format: FormatInfo) {
        console.log("_regformat=" + format.ext);
        this._format[format.ext] = format;
    }
    private _format: { [id: string]: FormatInfo } = {};

    GetFormatInfo(filename: string): FormatInfo {
        let ext = TTPathTool.GetExt(filename).toLowerCase();
        let f = this._format[ext];
        if (f != undefined) {
            console.log("_GetFormat ext=" + ext + "  " + f);
            return f;
        }
        for (var key in this._format) {
            let reg = new RegExp(key);


            if (reg.test(filename)) {
                console.log("test key succ =" + reg + " text=" + ext);
                return this._format[key];
            }
            else {
                console.log("test key fail =" + reg + " text=" + ext);
            }
        }
        return null;
    }

}